import React from 'react';
import { SelectDate, SelectDateComponent } from 'views/component/selectDate/selectDate';
import { timeData } from 'js/core/timeData';
import './selectTimeType.scss';
import { i18n } from 'js/core/i18n';

class SelectTimeType extends React.Component {
  constructor() {
    super()
    this.state = {
      start: null,
      end: null
    }
  }
  onClick = (value) => {
    if (this.props.onChange) {
      let time;
      if (this.state.start && this.state.end  && value !== 'hour') {
        time = { start: this.state.start, end: this.state.end }
      } else {
        time = timeData.getTimeRange(value);
      }
      this.props.onChange(value, time);
    }
  }
  dateOnChange = (value) => {
    this.setState({
      start: value[0],
      end: value[1]
    }, () => {
      if (this.props.onChange) {
        let time;
        if (this.state.start && this.state.end && this.props.value !== 'hour') {
          time = { start: this.state.start, end: this.state.end }
        } else {
          time = timeData.getTimeRange(this.props.value);
        }
        this.props.onChange(this.props.value, time);
      }
    })
  }
  clear = (e) => {
    e.stopPropagation();
    e.preventDefault();
    this.setState({
      start: null,
      end: null
    }, () => {
      if (this.props.onChange) {
        let time;
        if (this.state.start && this.state.end ) {
          time = { start: this.state.start, end: this.state.end }
        } else {
          time = timeData.getTimeRange(this.props.value);
        }
        this.props.onChange(this.props.value, time);
      }
    });
    return;
  }
  render() {
    let { start, end } = this.state;
    let label = this.props.data || [{ name: i18n.get('时'), value: 'hour' }, { name: i18n.get('日'), value: 'day' },
    { name: i18n.get('月'), value: 'month' }, { name: i18n.get('年'), value: 'year' }];
    let value = this.props.value;
    return <div className={"selectTimeType " + (this.props.className ? this.props.className : '')}>
      <div className="type flex-g-1 flex">
        {label.map(item => {
          let classText = '';
          if (item.value === value) {
            classText = ' active';
          }
          return <div className={"item flex-g-1" + classText} key={item.value} onClick={() => { this.onClick(item.value) }}>
            {item.name}</div>
        })}
      </div>
      {!this.props.data && <SelectDateComponent className={"self pl20 flex-vcenter" + (value === 'hour' ? ' v-hidden' : '')} onChange={this.dateOnChange} value={[start, end]}>
        <span className="fs26">{i18n.get('时间选择')}:</span><div className="itemInput ml20">{start}</div>-<div className="itemInput">{end}</div>
        {start && <span className="clear pl20" onClick={this.clear}>{i18n.get('清除')}</span>}
      </SelectDateComponent>}
    </div>
  }
}

export default SelectTimeType;